<template>
  <div class="file-list">
    <div v-for="(file, index) in files" :key="index" class="file-item">
      <div class="file-info">
        <span class="file-name">{{ file.name }}</span>
        <div class="file-actions">
          <a-button type="link" @click="handlePreview(file)">
            <eye-outlined /> 预览
          </a-button>
          <a-button type="link" @click="handleDownload(file)">
            <download-outlined /> 下载
          </a-button>
        </div>
      </div>
    </div>

    <!-- 预览弹窗 -->
    <a-modal
      v-model:visible="previewVisible"
      :title="currentFile?.name"
      width="80%"
      :footer="null"
      @cancel="handlePreviewClose"
    >
      <div class="preview-container">
        <iframe
          v-if="currentFile"
          :src="currentFile.url + '#view=FitH,top&type=accesspdf#scrollbars=0&toolbar=0&statusbar=0'"
          frameborder="0"
          style="width: 100%; height: 80vh;"
        ></iframe>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { EyeOutlined, DownloadOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';

interface FileItem {
  name: string;
  url: string;
}

const props = defineProps<{
  files: FileItem[];
}>();

const previewVisible = ref(false);
const currentFile = ref<FileItem | null>(null);

// 预览文件
const handlePreview = (file: FileItem) => {
  currentFile.value = file;
  previewVisible.value = true;
};

// 关闭预览
const handlePreviewClose = () => {
  previewVisible.value = false;
  currentFile.value = null;
};

// 下载文件
const handleDownload = async (file: FileItem) => {
  try {
    message.loading({ content: '正在准备下载...', key: 'download' });
    
    // 使用fetch获取文件
    const response = await fetch(file.url);
    if (!response.ok) throw new Error('下载失败');
    
    // 获取文件blob
    const blob = await response.blob();
    
    // 创建blob URL
    const blobUrl = window.URL.createObjectURL(blob);
    
    // 创建下载链接
    const link = document.createElement('a');
    link.href = blobUrl;
    link.download = file.name;
    document.body.appendChild(link);
    link.click();
    
    // 清理
    document.body.removeChild(link);
    window.URL.revokeObjectURL(blobUrl);
    
    message.success({ content: '下载已开始', key: 'download' });
  } catch (error) {
    console.error('下载失败:', error);
    message.error({ content: '下载失败，请稍后重试', key: 'download' });
  }
};
</script>

<style scoped>
.file-list {
  width: 100%;
}

.file-item {
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.file-item:last-child {
  border-bottom: none;
}

.file-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.file-name {
  color: #333;
  font-size: 14px;
}

.file-actions {
  display: flex;
  gap: 8px;
}

.preview-container {
  width: 100%;
  height: 100%;
  background: #f5f5f5;
}
</style> 